const { getHotSearchHistory } = require("../../../utils/request");
const config = require("../../../utils/config");

Page({
  data: {
    query: "", // 当前用户输入的查询内容
    history: [], // 用户的搜索历史，从本地存储中加载
    hotSearch: [], // 热门搜索，从接口获取
  },

  onLoad() {
    this.loadHistory(); // 加载本地存储的搜索历史
    this.loadHotSearch(); // 加载热门搜索数据
  },

  // 加载本地存储的搜索历史
  loadHistory() {
    const history = wx.getStorageSync("searchHistory") || [];
    this.setData({ history });
  },

  // 加载热门搜索数据
  async loadHotSearch() {
    try {
      const response = await getHotSearchHistory();
      console.log("热门搜索数据：" + response.data)
      if (response && response.data) {
        this.setData({ hotSearch: response.data });
      }
    } catch (error) {
      console.error("Failed to fetch hot search data:", error);
      wx.showToast({
        title: "Failed to load trending searches",
        icon: "none",
      });
    }
  },

  // 监听用户输入
  onInput(e) {
    this.setData({ query: e.detail.value.trim() });
  },

  // 搜索按钮点击事件
  onSearch() {
    const query = this.data.query.trim();
    if (!query) {
      wx.showToast({
        title: "Please enter a search term",
        icon: "none",
      });
      return;
    }

    // 更新历史搜索
    let history = this.data.history || []; // 确保历史搜索数组存在
    const existingIndex = history.indexOf(query);

    // 如果已存在，则删除原位置的记录
    if (existingIndex !== -1) {
      history.splice(existingIndex, 1);
    }

    // 将新搜索内容添加到最前面
    history.unshift(query);

    // 限制历史记录长度
    if (history.length > 10) history.pop();

    // 更新数据并保存到本地存储
    this.setData({ history });
    wx.setStorageSync("searchHistory", history);

    //跳转前清除搜索的关键字，防止返回时搜索框中还存在上次搜索的关键字
    this.setData({ query: "" });

    // 跳转到搜索结果页面
    wx.navigateTo({
      url: `/pages/search/search-result/search-result?query=${query}`,
    });
  },

  // 点击标签事件
  onTagTap(e) {
    const tag = e.currentTarget.dataset.tag;
    this.setData({ query: tag });
    this.onSearch();
  },

  // 清除历史搜索
  clearHistory() {
    wx.showModal({
      title: "Clear History",
      content: "Are you sure you want to clear all search history?",
      success: (res) => {
        if (res.confirm) {
          this.setData({ history: [] });
          wx.setStorageSync("searchHistory", []); // 清空本地存储
          wx.showToast({
            title: "Search history cleared",
            icon: "success",
          });
        }
      },
    });
  },
});
